<template>
  <my-container v-loading="pageLoading">
    <!--查询-->
    <template #header>
      <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>
        <el-form-item>
          <el-input
            v-model="filter.name"
            placeholder="名称"
            clearable
            @keyup.enter.native="onSearch"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-search" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" icon="el-icon-search" @click="onSearch">查询</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['admin_sysjob_add'])">
          <el-button type="primary" icon="el-icon-plus" @click="onAdd">新增</el-button>
        </el-form-item>

      </el-form>
    </template>

    <!--列表-->
    <el-table
      v-loading="listLoading"
      :data="data"
      border
      highlight-current-row
      :header-cell-style="{background:'#f9f9f9'}"
    >

      <el-table-column type="index" width="80" label="#" />
      <el-table-column prop="group" label="分组" width />
      <el-table-column prop="name" label="名称" width />
      <el-table-column prop="triggerType" label="触发器类型" width>
        <template #default="{row}">
          <el-tag :type="row.triggerType==0 ? 'success' : 'info'" disable-transitions>
            {{ row.triggerType==0 ? 'Simple' : 'CRON' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="有效期" :formatter="formatCreatedTime" width="200">
        <template slot-scope="scope">
          <span>{{ $moment( scope.row.startTime).format('YYYY-MM-DD') }}~{{ $moment(scope.row.endTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="cron" label="CRON表达式" width>
        <template #default="{row}">
          <span v-if="row.triggerType===0">--</span>
          <span v-if="row.triggerType===1">{{ row.cron }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="interval" label="时间间隔" width>
        <template #default="{row}">
          <span v-if="row.triggerType===0">{{ row.interval }}</span>
          <span v-if="row.triggerType===1">--</span>
        </template>
      </el-table-column>
      <el-table-column prop="repeatCount" label="重复次数" width>
        <template #default="{row}">
          <span v-if="row.triggerType===0">{{ row.repeatCount }}</span>
          <span v-if="row.triggerType===1">--</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width>
        <template #default="{row}">
          <el-tag v-if="row.status === 0" type="info" effect="dark" size="small">停止</el-tag>
          <el-tag v-else-if="row.status === 1" type="success" effect="dark" size="small">运行中</el-tag>
          <el-tag v-else-if="row.status === 2" type="warning" effect="dark" size="small">暂停</el-tag>
          <el-tag v-else-if="row.status === 3" type="primary" effect="dark" size="small">已完成</el-tag>
          <el-tag v-else type="danger" effect="dark" size="small">异常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">

        <template #default="{ $index, row }">
          <el-button v-if="[0, 2, 3].includes(row.status)&&checkPermission(['admin_sysjob_resume'])" type="primary" size="mini" @click="startJob(row)">启动</el-button>
          <el-button v-if="row.status ===1&&checkPermission(['admin_sysjob_pause'])" type="info" size="mini" @click="pauseJob(row)">暂停</el-button>
          <el-button v-if="[1, 2].includes(row.status)&&checkPermission(['admin_sysjob_stop']) " type="primary" size="mini" @click="stopJob(row)">停止</el-button>

          <el-button v-if="checkPermission(['admin_sysjob_log'])" type="warning" size="mini" @click="onShowLog(row)">日志</el-button>
          <my-confirm-button
            v-if="checkPermission(['admin_sysjob_delete'])"
            type="delete"
            :loading="row._loading"
            :validate-data="row"
            @click="onDelete($index, row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <my-pagination
      ref="pager"
      :total="total"
      @get-page="getJobList"
    />

    <!--新增窗口-->
    <el-dialog
      title="新增用户"
      :visible.sync="addFormVisible"
      :close-on-click-modal="false"
      width="40%"
    >

      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules" size="medium">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务分组" prop="group">
              <el-select v-model="addForm.group" placeholder="请选择分组" style="width:100%;">
                <el-option
                  v-for="item in groups"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="触发器" prop="triggerType">
              <el-radio-group v-model="addForm.triggerType">
                <el-radio :label="0">Simple</el-radio>
                <el-radio :label="1">CRON</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="任务类名" prop="jobClass">
              <el-select v-model="addForm.jobClass" placeholder="请选择任务" style="width:100%;" @change="selectOne">
                <el-option
                  v-for="item in jobClass"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="addForm.name" auto-complete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务编码" prop="code">
              <el-input v-model="addForm.code" auto-complete="off" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startTime">
              <el-date-picker
                v-model="addForm.startTime"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endTime">
              <el-date-picker
                v-model="addForm.endTime"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="addForm.triggerType===0?true:false">
          <el-col :span="12">
            <el-form-item label="间隔时间" prop="interval">
              <el-input v-model="addForm.interval" auto-complete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重复次数" prop="repeatCount">
              <el-input v-model="addForm.repeatCount" auto-complete="off" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="addForm.triggerType===1?true:false">
          <el-form-item label="CRON表达式" prop="cron">
            <el-input v-model="addForm.cron" auto-complete="off" />
          </el-form-item>
        </el-row>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="addFormVisible = false">取消</el-button>
          <my-confirm-button type="submit" :validate="addFormValidate" :loading="addLoading" @click="onAddSubmit" />
        </div>
      </template>
    </el-dialog>

    <!--日志记录-->
    <el-dialog title="日志查看" :visible.sync="taskLogVisible">
      <el-table :data="logs" border>
        <el-table-column property="type" label="类型" width="150">
          <template #default="{row}">
            <el-tag v-if="row.type === 0" type="success" size="small">信息</el-tag>
            <el-tag v-else-if="row.type === 1" type="info" size="small">调式</el-tag>
            <el-tag v-else-if="row.type === 2" type="warning" size="small">错误</el-tag>

          </template>
        </el-table-column>
        <el-table-column property="message" label="信息" width="500" />
        <el-table-column property="createTime" label="时间" />
      </el-table>
      <my-pagination
        ref="pager"
        :total="totalLog"
        @get-page="getLogList"
      />
    </el-dialog>

  </my-container>
</template>

<script>
import { formatTime } from '@/utils'
import { getJobList, removeJob, addJob, resumeJob, pause, stop, jobSelect, getLogs } from '@/api/admin/job'
import { getJobGroupList } from '@/api/admin/jobgroup'
import MyContainer from '@/components/my-container'
import MyConfirmButton from '@/components/my-confirm-button'

export default {
  name: 'Job',
  components: { MyContainer, MyConfirmButton },
  data() {
    return {
      filter: {
        name: ''
      },
      data: [],
      groups: [],
      jobClass: [],
      total: 0,
      totalLog: 0,
      id: '',
      logs: [],
      listLoading: false,
      pageLoading: false,
      taskLogVisible: false,
      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: '请输入任务名', trigger: 'blur' }],
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        jobClass: [{ required: true, message: '请选择类名', trigger: 'change' }],
        group: [{ required: true, message: '请选择分组', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
        endTime: [{ required: true, message: '请选择结束日期', trigger: 'blur' }],
        interval: [{ required: true, message: '请输入间隔', trigger: 'blur' }],
        cron: [{ required: true, message: '请输入cron表达式', trigger: 'blur' }],
        repeatCount: [{ required: true, message: '请输入重复次数', trigger: 'blur' }]
      },
      // 新增界面数据
      addForm: {
        name: '',
        code: '',
        triggerType: 0,
        interval: 5,
        repeatCount: 1,
        cron: ''
      }
    }
  },
  mounted() {
    this.getJobList()
  },
  beforeUpdate() {

  },
  methods: {

    // 日期格式化
    formatCreatedTime: function(row, column, time) {
      return formatTime(time, 'YYYY-MM-DD')
    },
    // 选择任务类名
    selectOne: function(value) {
      let obj = {}
      obj = this.jobClass.find((item) => {
        return item.value === value
      })
      const name = obj.label.substring(0, obj.label.indexOf('('))
      const code = obj.value.split(',')[0].split('.')[2]
      this.addForm.code = code
      this.addForm.name = name
    },
    // 查询
    onSearch() {
      this.$refs.pager.setPage(1)
      this.getJobList()
    },
    // 日志
    async getLogList() {
      var pager = this.$refs.pager.getPager()
      const params = {
        ...pager,
        id: this.id
      }
      const res = await getLogs(params)
      this.logs = res.data.rows
      this.totalLog = res.data.totalCount
    },
    // 日志
    onShowLog(row) {
      this.taskLogVisible = true
      this.id = row.id
      this.getLogList()
    },
    // 获取任务列表
    async getJobList() {
      this.$refs.pager.setPage(1)
      var pager = this.$refs.pager.getPager()
      const params = {
        ...pager,
        name: this.filter.name
      }
      this.listLoading = true
      const res = await getJobList(params)
      this.listLoading = false
      if (!res?.success) {
        return
      }

      this.total = res.data.totalCount
      const data = res.data.rows
      data.forEach(d => {
        d._loading = false
      })
      this.data = data
    },
    // 启动
    async startJob(row) {
      const res = await resumeJob(JSON.stringify(row.id))
      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('启动成功'),
        type: 'success'
      })
      this.getJobList()
    },
    // 暂停
    async pauseJob(row) {
      const res = await pause(JSON.stringify(row.id))
      if (!res?.success) {
        return
      }
      this.getJobList()
    },
    // 停止
    async stopJob(row) {
      const res = await stop(JSON.stringify(row.id))
      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('任务已成功停止'),
        type: 'success'
      })
      this.getJobList()
    },
    // 显示新增界面
    onAdd() {
      if (this.groups.length === 0) {
        this.pageLoading = true
        const params = {
          pageSize: 100,
          currentPage: 1
        }
        getJobGroupList(params).then(res => {
          if (res.success) {
            this.groups = res.data.rows
          }
        })
        jobSelect().then(res => {
          if (res.success) {
            this.jobClass = res.data
          }
        })

        this.pageLoading = false
      }
      this.addFormVisible = true
    },
    // 新增验证
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    // 新增
    async onAddSubmit() {
      this.addLoading = true
      const para = _.cloneDeep(this.addForm)

      const res = await addJob(para)
      this.addLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.addOk'),
        type: 'success'
      })
      this.$refs['addForm'].resetFields()
      this.addFormVisible = false
      this.getJobList()
    },
    // 关闭新增窗口
    closeAddForm() {
      this.$refs.addForm.resetFields()
    },

    // 删除
    async onDelete(index, row) {
      row._loading = true
      const res = await removeJob(JSON.stringify(row.id))
      row._loading = false
      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.deleteOk'),
        type: 'success'
      })
      this.getJobList()
    }
  }
}
</script>

